<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="queryParams.createTime"
            type="daterange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="驿站名称" prop="zdId">
          <el-tree-select
            v-model="queryParams.zdId"
            placeholder="全部"
            :data="yzOptions"
            filterable
            clearable
            check-strictly
            :render-after-expand="false"
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item label="取件码" prop="qjm">
          <el-input
            v-model="queryParams.qjm"
            placeholder="取件码"
            clearable
            @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item label="送达地址" prop="dz">
          <el-input
            v-model="queryParams.dz"
            placeholder="送达地址"
            clearable
            @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px" :class="{ 'mobile-buttons': isMobile }">
        <el-button v-hasPerm="['system:tomTable:add']" type="success" @click="handleOpenDialog1()">
          <template #icon>
            <Plus />
          </template>
          导入
        </el-button>
        <el-button
          v-hasPerm="['system:tomTable:hz-download']"
          type="primary"
          @click="handleHzExport"
        >
          <template #icon>
            <Download />
          </template>
          汇总表
        </el-button>
        <el-button v-hasPerm="['system:tomTable:dz-download']" type="info" @click="handleDzExport">
          <template #icon>
            <Download />
          </template>
          地址表
        </el-button>
        <el-button
          v-if="!isMobile"
          v-hasPerm="['system:tomTable:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon>
            <Delete />
          </template>
          删除
        </el-button>
      </div>

      <!-- 桌面端表格视图 -->
      <el-table
        v-if="!isMobile"
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column
          key="createTime"
          label="创建时间"
          prop="createTime"
          width="200"
          align="center"
        />
        <el-table-column
          key="zdName"
          label="驿站名称"
          prop="zdName"
          min-width="200"
          align="center"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          key="qjm"
          label="取件码"
          prop="qjm"
          min-width="150"
          align="center"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          key="dz"
          label="送达地址"
          prop="dz"
          min-width="150"
          align="center"
          :show-overflow-tooltip="true"
        />
        <el-table-column fixed="right" label="操作" align="center" width="180">
          <template #default="scope">
            <el-button
              v-hasPerm="['system:tomTable:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon>
                <Edit />
              </template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['system:tomTable:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon>
                <Delete />
              </template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 移动端卡片视图 -->
      <div v-else class="mobile-card-container">
        <el-card v-for="item in pageData" :key="item.id" class="mobile-card" shadow="hover">
          <div class="card-content">
            <div class="card-row">
              <span class="card-label">创建时间:</span>
              <span class="card-value">{{ item.createTime }}</span>
            </div>
            <div class="card-row">
              <span class="card-label">驿站名称:</span>
              <span class="card-value">{{ item.zdName }}</span>
            </div>
            <div class="card-row">
              <span class="card-label">取件码:</span>
              <span class="card-value">{{ item.qjm }}</span>
            </div>
            <div class="card-row">
              <span class="card-label">送达地址:</span>
              <span class="card-value">{{ item.dz }}</span>
            </div>
            <div class="card-actions">
              <el-button
                v-hasPerm="['system:tomTable:edit']"
                type="primary"
                size="small"
                @click="handleOpenDialog(item.id)"
              >
                <template #icon>
                  <Edit />
                </template>
                编辑
              </el-button>
              <el-button
                v-hasPerm="['system:tomTable:delete']"
                type="danger"
                size="small"
                @click="handleDelete(item.id)"
              >
                <template #icon>
                  <Delete />
                </template>
                删除
              </el-button>
            </div>
          </div>
        </el-card>
      </div>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 汤姆代取表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="isMobile ? '90%' : '500px'"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="驿站名称" prop="zdId">
          <el-tree-select
            v-model="formData.zdId"
            placeholder="请选择驿站名称"
            :data="yzOptions"
            filterable
            check-strictly
            :render-after-expand="false"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="取件码" prop="qjm">
          <el-input v-model="formData.qjm" placeholder="取件码" />
        </el-form-item>

        <el-form-item label="送达地址" prop="dz">
          <el-input v-model="formData.dz" placeholder="送达地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 汤姆代取表单弹窗 -->
    <el-dialog
      v-model="dialog1.visible"
      :title="dialog1.title"
      :width="isMobile ? '90%' : '500px'"
      @close="handleCloseDialog1"
    >
      <el-form ref="dataFormRef1" :model="formData1" :rules="rules1" label-width="80px">
        <el-form-item label="驿站名称" prop="zdId">
          <el-tree-select
            v-model="formData1.zdId"
            placeholder="请选择驿站名称"
            :data="yzOptions"
            filterable
            check-strictly
            :render-after-expand="false"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="识别内容" prop="remark">
          <el-input
            v-model="formData1.remark"
            type="textarea"
            placeholder="请将取件码按照约定的识别方式粘贴在此处"
            :rows="isMobile ? 5 : 10"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit1()">确定</el-button>
          <el-button @click="handleCloseDialog1()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "TomTable",
  inheritAttrs: false,
});

import TomTableAPI, {
  TomTablePageVO,
  TomTableForm,
  TomTablePageQuery,
} from "@/api/system/tom-table";

import TomYzTableAPI from "@/api/system/tom-yz-table";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const dataFormRef1 = ref(ElForm);

const loading = ref(false);
const loading1 = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

// 移动端检测
const isMobile = ref(false);

const queryParams = reactive<TomTablePageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 下拉数据源
const yzOptions = ref<OptionType[]>();

// 汤姆代取表格数据
const pageData = ref<TomTablePageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

const dialog1 = reactive({
  title: "",
  visible: false,
});

// 汤姆代取表单数据
const formData = reactive<TomTableForm>({});

const formData1 = reactive<TomTableForm>({});

// 汤姆代取表单校验规则
const rules = reactive({
  zdId: [{ required: true, message: "选择驿站名称", trigger: "blur" }],
  qjm: [{ required: true, message: "请输入取件码", trigger: "blur" }],
});

const rules1 = reactive({
  zdId: [{ required: true, message: "选择驿站名称", trigger: "blur" }],
  remark: [{ required: true, message: "请填入识别内容", trigger: "blur" }],
});

// 检测是否为移动端
const checkIsMobile = () => {
  isMobile.value = window.innerWidth < 768;
};

function handleHzExport() {
  // 如果queryParams的zdId是空的则提示 请选择驿站名称!
  if (!queryParams.zdId) {
    ElMessage.error("请选择驿站名称!");
    return;
  }
  TomTableAPI.exportHz(queryParams).then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(response.headers["content-disposition"].split(";")[1].split("=")[1]);
    const fileType =
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";
    const blob = new Blob([fileData], { type: fileType });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}

function handleDzExport() {
  // 如果queryParams的zdId是空的则提示 请选择驿站名称!
  if (!queryParams.zdId) {
    ElMessage.error("请选择驿站名称!");
    return;
  }
  TomTableAPI.exportDz(queryParams).then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(response.headers["content-disposition"].split(";")[1].split("=")[1]);
    const fileType =
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

    const blob = new Blob([fileData], { type: fileType });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}

/** 查询汤姆代取 */
function handleQuery() {
  loading.value = true;
  TomTableAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置汤姆代取查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开汤姆代取弹窗 */
async function handleOpenDialog1(id?: number) {
  dialog1.visible = true;
  // 加载下拉数据源
  yzOptions.value = await TomYzTableAPI.getOptions();
  if (id) {
    dialog.title = "编辑汤姆代取";
    TomTableAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog1.title = "导入取件码+送达地址";
  }
}

/** 打开汤姆代取弹窗 */
async function handleOpenDialog(id?: number) {
  dialog.visible = true;
  // 加载下拉数据源
  yzOptions.value = await TomYzTableAPI.getOptions();
  if (id) {
    dialog.title = "编辑汤姆代取";
    TomTableAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "导入取件码+送达地址";
  }
}

/** 提交汤姆代取表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        TomTableAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        TomTableAPI.add(formData)
          .then(() => {
            ElMessage.success("导入成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 提交汤姆代取表单 */
function handleSubmit1() {
  dataFormRef1.value.validate((valid: any) => {
    if (valid) {
      loading1.value = true;
      TomTableAPI.add(formData1)
        .then(() => {
          ElMessage.success("导入成功");
          handleCloseDialog1();
          handleResetQuery();
        })
        .finally(() => (loading1.value = false));
    }
  });
}

/** 关闭汤姆代取弹窗 */
function handleCloseDialog1() {
  dialog1.visible = false;
  dataFormRef1.value.resetFields();
  dataFormRef1.value.clearValidate();
  formData1.id = undefined;
}

/** 关闭汤姆代取弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除汤姆代取 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      TomTableAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(async () => {
  // 检测是否为移动端
  checkIsMobile();
  window.addEventListener("resize", checkIsMobile);

  // 加载区域下拉数据源
  yzOptions.value = await TomYzTableAPI.getOptions();
  handleQuery();
});

onUnmounted(() => {
  window.removeEventListener("resize", checkIsMobile);
});
</script>

<style scoped>
.mobile-card-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.mobile-card {
  width: 100%;
}

.card-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.card-row {
  display: flex;
  flex-wrap: wrap;
}

.card-label {
  font-weight: bold;
  margin-right: 8px;
  flex-shrink: 0;
}

.card-value {
  flex: 1;
}

.card-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 8px;
}

@media (max-width: 767px) {
  .search-bar .el-form-item {
    display: block;
    margin-bottom: 12px;
  }

  .search-bar .el-form-item .el-form-item__content {
    width: 100%;
  }

  .search-bar .el-form-item .el-select,
  .search-bar .el-form-item .el-date-editor,
  .search-bar .el-form-item .el-input {
    width: 100% !important;
  }
}
</style>

<style scoped>
/* 现有的样式... */

.mobile-buttons {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}

@media (max-width: 767px) {
  .mobile-buttons {
    grid-template-columns: repeat(3, 1fr);
  }

  .mobile-buttons .el-button {
    margin: 0;
    justify-content: center;
  }

  /* 如果屏幕特别小，可以只显示一个按钮每行 */
  @media (max-width: 480px) {
    .mobile-buttons {
    }
  }

  /* 在较大移动屏幕上显示4个按钮 */
  @media (min-width: 481px) and (max-width: 767px) {
    .mobile-buttons {
      grid-template-columns: repeat(4, 1fr);
    }
  }

  .search-bar .el-form-item {
    display: block;
    margin-bottom: 12px;
  }

  .search-bar .el-form-item .el-form-item__content {
    width: 100%;
  }

  .search-bar .el-form-item .el-select,
  .search-bar .el-form-item .el-date-editor,
  .search-bar .el-form-item .el-input {
    width: 100% !important;
  }
}
</style>
